<?php
namespace app\admin\controller\business;

use app\common\controller\AdminController;
use think\app;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;

class Account extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = app('app\common\model\mall\Account');
        $this->storemodel = app('app\common\model\mall\Store');

    }

    public function get_where($arr=[]){
        $admin = Session::get('admin');
        $array[]=['store_id','=',$admin['store_id']];
        $array[]=['type','=',2];
        if(isset($arr['title']) && !empty($arr['title'])){
            $array[] = ['title','like','%'.$arr['title'].'%'];
        }
        return $array;
    }
    public function get_other(){
        $model = app('app\common\model\common\Categories');

        $data = $model->field('id,name,parent_id')->with(['childs'=>function($query){
            $query->where(['type'=>2])->with(['childs'=>function($query){
                $query->where(['type'=>2])->select();
            }]);
        }
        ])->where(['parent_id'=>0,'type'=>2])->order('sort asc')->select();

        View::assign('data',$data);
    }
    public function get_with(){
        return ['category'];
    }

    public function action(){

        $param= $this->request->param();

        try{
            $row = $this->model->where('id',$param['id'])->find();
            $row->save($param);
            $admin = Session::get('admin');
            $rt = $this->model->where(['is_sale'=>1,'type'=>2,'store_id'=>$admin['store_id']])->find();

            $store = $this->storemodel->where('id',$admin['store_id'])->find();
            if(!empty($rt)){
                $store->save(['id'=>$store['id'],'is_sale'=>1]);
            }else{
                $store->save(['id'=>$store['id'],'is_sale'=>0]);
            }

        }catch (\Exception $exception){
            return json(['code'=>1,'msg'=>$exception->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'操作成功']);
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();

            // 启动事务
            Db::startTrans();
            try {
                $rule = [];
                if (method_exists($this, 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }

                $this->validate($data, $rule);
                $data['app_id'] = $this->model->getApp();
                
                if(empty($data['image'])){
                    return json(['code'=>0,'msg'=>'添加失败，请上传图片','data'=>'请上传图片']);
                }
                if(empty($data['address'])){
                    return json(['code'=>0,'msg'=>'请填写上课地址']);
                }else{
                    if(count($data['address'])>10){
                        return json(['code'=>0,'msg'=>'上课地址最多可填写10个']);
                    }
                }

                $data['address'] = implode(',',$data['address']);
                if(isset($data['subject'])){
                    if(count($data['subject'])>10){
                        return json(['code'=>0,'msg'=>'科目最多可填写10个']);
                    }
                    $data['subject'] = implode(',',$data['subject']);
                }
                if($data['price'] <= 0 ){
                    return json(['code'=>0,'msg'=>'价格不能为空或者0']);
                }elseif($data['is_tuan'] ==1 && ($data['more_price'] <= 0 || $data['num'] <=1)){
                    return json(['code'=>0,'msg'=>'团购价或者参团人数有误']);
                }
                if(empty($data['work'])){
                    return json(['code'=>0,'msg'=>'添加失败，请填写上课时间']);
                }

                $data['image']=implode(',',$data['image']);
                $admin = Session::get('admin');
                $data['store_id'] = $admin['store_id'];
                $data['type'] = 2;

                $data['total_number'] = array_sum($data['numbers']);
                $data['alone_number'] = $data['total_number'];
                $save = $this->model->save($data);
                if(!empty($data['work'])){
                    /*获取章节数据*/
                    $item=[];
                    foreach ($data['work'] as $k=>$v){
                        $item[$k]['work'] = $v;
                        $item[$k]['sort'] = $data['sort'][$k];
                        $item[$k]['account_price'] = $data['price'];
                        $item[$k]['number'] = $data['numbers'][$k];
                        $item[$k]['article_id'] = $this->model->id;
                    }
                    $itemmodel = app('app\common\model\media\AccountItem');
                    $itemmodel->saveAll($item);
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        if(method_exists($this,'get_other')){
            $this->get_other($this->request->param() ?? []);
        }
        return view();
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $itemmodel = app('app\common\model\media\AccountItem');
        $id = $this->request->param('id');

        $row = $this->model->find($id);

        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            try {
                $data = $this->request->post();
                $rule = [];
                if (method_exists($this, 'get_check_rule')){
                    $rule = $this->get_check_rule($post ?? []);
                }

                $this->validate($data, $rule);

                if(empty($data['image'])){
                    return json(['code'=>0,'msg'=>'更新失败','data'=>'请上传图片']);
                }
                if(empty($data['address'])){
                    return json(['code'=>0,'msg'=>'请填写上课地址','data'=>'']);
                }else{
                    if(count($data['address'])>10){
                        return json(['code'=>0,'msg'=>'上课地址最多可填写10个','data'=>'']);
                    }
                }
                $data['address'] = implode(',',$data['address']);
                if(isset($data['subject'])){
                    if(count($data['subject'])>10){
                        return json(['code'=>0,'msg'=>'科目最多可填写10个']);
                    }
                    $data['subject'] = implode(',',$data['subject']);
                }
                if($data['price'] <= 0 ){
                    return json(['code'=>0,'msg'=>'价格不能为空或者0']);
                }elseif($data['is_tuan'] ==1 && ($data['more_price'] <= 0 || $data['num'] <=1)){

                    return json(['code'=>0,'msg'=>'团购价或者参团人数有误']);

                }
                if(empty($data['work'])){
                    return json(['code'=>0,'msg'=>'添加失败，请填写上课时间']);
                }
//                dd($data);
                $data['image']=implode(',',$data['image']);
                $data['total_number'] = array_sum($data['numbers']);
                $data['alone_number'] = $data['total_number'];
                $data['status'] = 0;
                $save =  $row->save($data);
                /*获取章节数据*/
                //先删除不存在attr_id之中的sku
                if(empty($data['attr_id']) || !isset($data['attr_id'])){
                    $data['attr_id'] =[];
                }

                $ids  = $itemmodel->where('article_id',$row['id'])->whereNotIn('id',$data['attr_id'])->select();
                $ids->delete();
                if(!empty($data['work'])){

                    $item=[];
                    foreach ($data['work'] as $k=>$v){
                        $item[$k]['work'] = $v;
                        $item[$k]['sort'] = $data['sort'][$k];
                        $item[$k]['account_price'] = $data['price'];
                        $item[$k]['number'] = $data['numbers'][$k];
                        $item[$k]['article_id'] = $row['id'];
                        if(isset($data['attr_id'][$k])){
                            $itemmodel->where('id',$data['attr_id'][$k])->update($item[$k]);
                        }else{
                            $itemmodel->create($item[$k]);
                        }
                    }
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error($e->getMessage());
        }
        $row['address'] = explode(',',$row['address']);
        if(!empty($row['subject'])){
            $row['subject'] = explode(',',$row['subject']);
        }
        View::assign('row', $row);
        if(method_exists($this,'get_other')){
            $this->get_other($this->request->param() ?? []);
        }

        return view('', compact('row'));
    }

}